package com.csw.android.androidtest.module.event;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.csw.android.androidtest.ui.LogViewFragment;

/**
 * 本地广播测试
 * <p>
 * 鉴于广播机制的繁（用起来麻烦）重（跨进程需要序列化反序列化）
 * <p>
 * android提供了本地广播，顾名思义，这个广播只有进程内可用，广播的发送与接收都要通过
 * LocalBroadcastManager.getInstance获取的实例进行操作。
 * 本身的实现就是一个观察者模式，代码不多，感兴趣可以研究。
 */
public class LocalBroadcastTest extends LogViewFragment {
    /**
     * 广播接收器
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String action = intent.getAction();
                if (action != null) {
                    switch (action) {
                        case "LocalBroadcastTest1":
                            String v1 = intent.getStringExtra("key1");
                            int v2 = intent.getIntExtra("key2", 0);
                            double v3 = intent.getDoubleExtra("key3", 0.0);
                            if (v1 != null) {
                                logView.addLog(v1);
                            }
                            if (v2 != 0) {
                                logView.addLog(v2);
                            }
                            if (v3 != 0) {
                                logView.addLog(v3);
                            }
                            break;
                        case "LocalBroadcastTest2":
                            break;
                    }
                }
            }
        }
    };

    @Override
    public void initListener() {
        super.initListener();
        //注册本地广播监听
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("LocalBroadcastTest1");
        intentFilter.addAction("LocalBroadcastTest2");
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, intentFilter);
    }

    @Override
    public void initData() {
        super.initData();
        //通过本地广播发送数据
        Intent intent = new Intent("LocalBroadcastTest1");
        intent.putExtra("key1", "stringValue");
        intent.putExtra("key2", 2);
        intent.putExtra("key3", 2.0);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }

    @Override
    public void onDestroyView() {
        //注销监听
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
        super.onDestroyView();
    }
}
